package com.gla.giliair.web.admin;

import com.gla.giliair.entity.Customer;
import com.gla.giliair.util.IndentityUtil;
import com.gla.giliair.util.MD5Util;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.util.PatternUtil;
import com.gla.giliair.web.BaseController;
import com.gla.giliair.web.vo.CustomerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/25 20:37
 */
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("/api/adminX")
public class AdminUserController extends BaseController {
    @ApiOperation(value = "获取全部用户列表", notes = "获取全部用户列表，有多种排序方式", produces = "application/json")
    @GetMapping("/findAllUser")
    @ResponseBody
    public Map<String, Object> findAllUser(//排序关键词：customerId、username、password、
                                           // nickname、gender、phone、email、
                                           // customerType、score、IDNumber、realname、birthday、
                                           // createTime、updateTime、isDeleted
                                           //不填关键词默认按id逆向排序
                                           @RequestParam(value = "sort", defaultValue = "customerId") String sort,
                                           //正反序只对关键词生效
                                           @RequestParam(value = "isASC", defaultValue = "false") boolean isASC,
                                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "pageSize", defaultValue = "16") Integer pageSize) {
        return userService.findAllUsers(sort, isASC, page, pageSize);
    }

    @ApiOperation(value = "搜索用户列表", notes = "搜索用户列表，有多种排序方式", produces = "application/json")
    @PostMapping("/searchUser")
    @ResponseBody
    public Map<String, Object> searchUser(//排序关键词：customerId、username、password、
                                          // nickname、gender、phone、email、
                                          // customerType、score、IDNumber、realname、birthday、
                                          // createTime、updateTime、isDeleted
                                          //不填关键词默认按id逆向排序
                                          @RequestParam(value = "sort", defaultValue = "customerId") String sort,
                                          //正反序只对关键词生效
                                          @RequestParam(value = "isASC", defaultValue = "false") boolean isASC,
                                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "pageSize", defaultValue = "16") Integer pageSize,
                                          //准确搜索参数：客户种类；模糊搜索参数：姓名、用户名、电话、邮箱、身份证号
                                          @RequestBody CustomerVO searchParams) {
        return userService.searchCustomers(sort, isASC, page, pageSize, searchParams);
    }

    @ApiOperation(value = "添加用户信息", notes = "添加用户信息", produces = "application/json")
    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(@RequestParam("username") String username,
                                       @RequestParam("password") String password,
                                       @RequestParam(value = "nickname", required = false) String nickname,
                                       @RequestParam(value = "gender", required = false) Integer gender,
                                       @RequestParam(value = "phone", required = false) String phone,
                                       @RequestParam(value = "email", required = false) String email,
                                       @RequestParam(value = "customerType", required = false) Integer customerType,
                                       @RequestParam(value = "score", required = false) Integer score,
                                       @RequestParam(value = "IDNumber", required = false) String IDNumber,
                                       @RequestParam(value = "realname", required = false) String realname,
                                       @RequestParam(value = "birthday", required = false) String birthday) {
        if (!StringUtils.hasText(username)) {
            return MapGenerator.getRes(500, "请输入用户名！");
        }
        if (!StringUtils.hasText(password)) {
            return MapGenerator.getRes(501, "请输入密码！");
        }
        Customer customer = new Customer();
        customer.setUsername(username);
        customer.setPassword(MD5Util.md5Encode(password));

        if (StringUtils.hasText(nickname)) {
            customer.setNickname(nickname);
        }
        if (new Integer(0).equals(gender) || new Integer(1).equals(gender) || new Integer(2).equals(gender)) {
            customer.setGender(gender);
        }
        if (StringUtils.hasText(phone)) {
            if (PatternUtil.isPhone(phone)) {
                customer.setPhone(phone);
            }
        }
        if (StringUtils.hasText(email)) {
            if (PatternUtil.isEmail(email)) {
                customer.setEmail(email);
            }
        }
        if (new Integer(0).equals(customerType) || new Integer(1).equals(customerType) || new Integer(2).equals(customerType)) {
            customer.setCustomerType(customerType);
        }
        if (score != null) {
            customer.setScore(score);
        }
        if (StringUtils.hasText(IDNumber) && StringUtils.hasText(realname)) {
            try {
                if (IndentityUtil.idCheck(IDNumber, realname)) {
                    customer.setIdNumber(IDNumber);
                    customer.setRealname(realname);
                } else {
                    //身份证不合法，更新失败
                    return MapGenerator.getRes(501, "身份证号不存在，或与真实姓名不匹配！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.hasText(birthday)) {
            Date birthdayDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                birthdayDate = sdf.parse(birthday);
                customer.setBirthday(birthdayDate);
            } catch (ParseException e) {
                e.printStackTrace();
                return MapGenerator.getRes(502, "生日格式不正确！");
            }
        }
        return userService.addUser(customer);
    }

    @ApiOperation(value = "修改用户信息", notes = "修改用户信息，身份证号和真名要成对更新", produces = "application/json")
    @PostMapping("/modifyUser")
    @ResponseBody
    public Map<String, Object> modifyUser(@RequestParam("customerId") Long customerId,
                                          @RequestParam(value = "username", required = false) String username,
                                          @RequestParam(value = "password", required = false) String password,
                                          @RequestParam(value = "nickname", required = false) String nickname,
                                          @RequestParam(value = "gender", required = false) Integer gender,
                                          @RequestParam(value = "phone", required = false) String phone,
                                          @RequestParam(value = "email", required = false) String email,
                                          @RequestParam(value = "customerType", required = false) Integer customerType,
                                          @RequestParam(value = "score", required = false) Integer score,
                                          @RequestParam(value = "IDNumber", required = false) String IDNumber,
                                          @RequestParam(value = "realname", required = false) String realname,
                                          @RequestParam(value = "birthday", required = false) String birthday) {
        if (customerId == null) {
            return MapGenerator.getRes(500, "请输入用户id！");
        }
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        if (StringUtils.hasText(username)) {
            customer.setUsername(username);
        }
        if (StringUtils.hasText(password)) {
            customer.setPassword(MD5Util.md5Encode(password));
        }
        if (StringUtils.hasText(nickname)) {
            customer.setNickname(nickname);
        }
        if (new Integer(0).equals(gender) || new Integer(1).equals(gender) || new Integer(2).equals(gender)) {
            customer.setGender(gender);
        }
        if (StringUtils.hasText(phone)) {
            if (PatternUtil.isPhone(phone)) {
                customer.setPhone(phone);
            }
        }
        if (StringUtils.hasText(email)) {
            if (PatternUtil.isEmail(email)) {
                customer.setEmail(email);
            }
        }
        if (new Integer(0).equals(customerType) || new Integer(1).equals(customerType) || new Integer(2).equals(customerType)) {
            customer.setCustomerType(customerType);
        }
        if (score != null) {
            customer.setScore(score);
        }
        if (StringUtils.hasText(IDNumber) && StringUtils.hasText(realname)) {
            try {
                if (IndentityUtil.idCheck(IDNumber, realname)) {
                    customer.setIdNumber(IDNumber);
                    customer.setRealname(realname);
                } else {
                    //身份证不合法，更新失败
                    return MapGenerator.getRes(501, "身份证号不存在，或与真实姓名不匹配！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.hasText(birthday)) {
            Date birthdayDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                birthdayDate = sdf.parse(birthday);
                customer.setBirthday(birthdayDate);
            } catch (ParseException e) {
                e.printStackTrace();
                return MapGenerator.getRes(502, "生日格式不正确！");
            }
        }
        return userService.modifyUser(customer);
    }

    @ApiOperation(value = "冻结/解冻用户信息", notes = "冻结/解冻用户信息", produces = "application/json")
    @PostMapping("/lockUser")
    @ResponseBody
    public Map<String, Object> lockUser(@RequestParam("customerId") Long customerId,
                                        //不填是否冻结，默认冻结
                                        @RequestParam(value = "isLocked", defaultValue = "true") boolean isLocked) {
        if (customerId == null) {
            return MapGenerator.getRes(500, "请输入用户id！");
        }
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        if (isLocked) {
            customer.setIsLocked(1);
        } else {
            customer.setIsLocked(0);
        }
        Map<String, Object> res = userService.modifyUser(customer);
        if ((Integer) res.get("status") == 200) {
            if (isLocked) {
                return MapGenerator.getRes(200, "冻结用户成功!");
            } else {
                return MapGenerator.getRes(201, "解冻用户成功!");
            }
        }
        return res;
    }
}
